<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>海滩</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
    </style>
</head>

<body>
    <canvas class="webgl"></canvas>
</body>
<script type="module">
    import * as THREE from "three";
    import { Water } from 'three/examples/jsm/objects/Water';
    import { Sky } from 'three/examples/jsm/objects/Sky';
    import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
    import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
    // import { TWEEN } from "three/examples/jsm/libs/tween.module.min";
    import waterTexture from './images/waterTexture.png';
    // import flamingoModel from './models/Flamingo.glb';

    const clock = new THREE.Clock();
    const raycaster = new THREE.Raycaster()
    const sizes = {
        width: window.innerWidth,
        height: window.innerHeight
    }
    console.log("wi", window);

    const renderer = new THREE.WebGLRenderer({
        canvas: document.querySelector('canvas.webgl'),
        antialias: true
    });
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
    renderer.setSize(sizes.width, sizes.height);
    // 设置渲染效果
    renderer.toneMapping = THREE.ACESFilmicToneMapping;
    // 创建场景
    const scene = new THREE.Scene();
    // 创建相机
    const camera = new THREE.PerspectiveCamera(55, sizes.width / sizes.height, 1, 20000);
    camera.position.set(0, 600, 1600);
    // 添加镜头轨道控制器
    const controls = new OrbitControls(camera, renderer.domElement);

    controls.target.set(0, 0, 0);
    controls.enableDamping = true;
    controls.enablePan = false;
    controls.maxPolarAngle = 1.5;
    controls.minDistance = 50;
    controls.maxDistance = 1200;
    // 添加环境光
    const ambientLight = new THREE.AmbientLight(0xffffff, .8);
    scene.add(ambientLight);
    // 添加平行光
    const dirLight = new THREE.DirectionalLight(0xffffff, 1);
    dirLight.color.setHSL(.1, 1, .95);
    dirLight.position.set(-1, 1.75, 1);
    dirLight.position.multiplyScalar(30);
    scene.add(dirLight);
    // 页面缩放监听并重新更新场景和相机
    window.addEventListener('resize', () => {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
    }, false);


    const waterGeometry = new THREE.PlaneGeometry(10000, 10000);

    const water = new Water(waterGeometry, {
        textureWidth: 512,
        textureHeight: 512,
        waterNormals: new THREE.TextureLoader().load(waterTexture, texture => {
            texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
        }),
        sunDirection: new THREE.Vector3(),
        sunColor: 0xffffff,
        waterColor: 0x0072ff,
        distortionScale: 4,
        fog: scene.fog !== undefined
    });
    water.rotation.x = - Math.PI / 2;
    scene.add(water);

    const sky = new Sky();
    sky.scale.setScalar(10000);
    scene.add(sky);
    const skyUniforms = sky.material.uniforms;
    skyUniforms['turbidity'].value = 20;
    skyUniforms['rayleigh'].value = 2;
    skyUniforms['mieCoefficient'].value = 0.005;
    skyUniforms['mieDirectionalG'].value = 0.8;
    // 太阳
    const sun = new THREE.Vector3();
    const pmremGenerator = new THREE.PMREMGenerator(renderer);
    const phi = THREE.MathUtils.degToRad(88);
    const theta = THREE.MathUtils.degToRad(180);
    sun.setFromSphericalCoords(1, phi, theta);
    sky.material.uniforms['sunPosition'].value.copy(sun);
    water.material.uniforms['sunDirection'].value.copy(sun).normalize();
    scene.environment = pmremGenerator.fromScene(sky).texture;

    // const material = new THREE.ShaderMaterial({
    //     side: THREE.DoubleSide,
    //     transparent: true,
    //     uniforms: {},
    //     vertexShader: vertexShader,
    //     fragmentShader: fragmentShader
    // });
    // const geometry = new THREE.TorusGeometry(200, 10, 50, 100);
    // const torus = new THREE.Mesh(geometry, material);
    // torus.opacity = .1;
    // torus.position.set(0, -50, -400);
    // scene.add(torus);

    const manager = new THREE.LoadingManager();
    manager.onProgress = async (url, loaded, total) => {
        if (Math.floor(loaded / total * 100) === 100) {
            // this.setState({ loadingProcess: Math.floor(loaded / total * 100) });
            Animations.animateCamera(camera, controls, { x: 0, y: 40, z: 140 }, { x: 0, y: 0, z: 0 }, 4000, () => {
                // this.setState({ sceneReady: true });
            });
        } else {
            // this.setState({ loadingProcess: Math.floor(loaded / total * 100) });
        }
    };
    const loader = new GLTFLoader(manager);
    let mixers = []

    loader.load('./models/Flamingo.glb', gltf => {
        const mesh = gltf.scene.children[0];
        mesh.scale.set(.35, .35, .35);
        mesh.position.set(-100, 80, -300);
        mesh.rotation.y = - 1;
        mesh.castShadow = true;
        scene.add(mesh);
        const mixer = new THREE.AnimationMixer(mesh);
        mixer.clipAction(gltf.animations[0]).setDuration(1.2).play();
        mixers.push(mixer);
    });




    const animate = () => {
        requestAnimationFrame(animate);
        water.material.uniforms['time'].value += 1.0 / 60.0;
        controls && controls.update();
        const delta = clock.getDelta();
        mixers && mixers.forEach(item => {
            item.update(delta);
        });
        const timer = Date.now() * 0.0005;
        // TWEEN && TWEEN.update();
        camera && (camera.position.y += Math.sin(timer) * .05);
        // if (this.state.sceneReady) {
        //     // 遍历每个点
        //     for (const point of points) {
        //         // 获取2D屏幕位置
        //         const screenPosition = point.position.clone();
        //         screenPosition.project(camera);
        //         raycaster.setFromCamera(screenPosition, camera);
        //         const intersects = raycaster.intersectObjects(scene.children, true);
        //         if (intersects.length === 0) {
        //             // 未找到相交点，显示
        //             point.element.classList.add('visible');
        //         } else {
        //             // 找到相交点
        //             // 获取相交点的距离和点的距离
        //             const intersectionDistance = intersects[0].distance;
        //             const pointDistance = point.position.distanceTo(camera.position);
        //             // 相交点距离比点距离近，隐藏；相交点距离比点距离远，显示
        //             intersectionDistance < pointDistance ? point.element.classList.remove('visible') : point.element.classList.add('visible');
        //         }
        //         const translateX = screenPosition.x * sizes.width * 0.5;
        //         const translateY = - screenPosition.y * sizes.height * 0.5;
        //         point.element.style.transform = `translateX(${translateX}px) translateY(${translateY}px)`;
        //     }
        // }
        renderer.render(scene, camera);
    }
    animate();


</script>

</html>